<?php

// +----------------------------------------------------------------------

// | Description: 客户

// +----------------------------------------------------------------------

// | Author: zl

// +----------------------------------------------------------------------



namespace app\crm\controller;

use app\admin\controller\ApiCommon;

use think\response\Json;

use think\facade\Db;

use think\facade\Request;


use app\crm\model\Customer as CustomerModel;

use app\crm\model\CustomerConfig as CustomerConfigModel;

use app\mini\model\SendUrlModel;


class WxScriptModel extends ApiCommon
{
    protected $customerModel;

    protected $customerConfigModel;

     /**

     * 用于判断权限

     * @permission 无限制

     * @allow 登录用户可访问

     * @other 其他根据系统设置

     **/

    public function initialize()

    {

        $action = [

            'permission' => ['get_unionid_length','get_unionid','get_wx_access_token','get_access_token_wx'],

            'allow' => ['users', 'info']

        ];

        event('CheckAuth',$action);

        $request = $this->request;

        $a = strtolower($request->action());



        $this->customerModel = new CustomerModel();

        $this->customerConfigModel = new CustomerConfigModel();

        if (!in_array($a, $action['permission'])) {

            parent::initialize();

        }

    }

    /**
     * 获取公众号用户数量
     * @
     */
    public function get_unionid_length(): Json
    {
        // echo '脚本';
        $length = Db::name('wx_gzh_fans')->count();
        
        return resultArray(['error' => '脚本', 'data'=>['length' => $length]]);
    }

    /**
     * 获取公众号用户unionid
     * @
     */
    public function get_unionid(): Json
    {

        $model = new SendUrlModel();

        $param = request()->param();

        $limit = $param['num'];

        $openInfo = Db::name('wx_gzh_fans')->limit($limit,1)->select()->toArray();

        // echo "<pre>";
        // print_r($openInfo);
        // echo "</pre>";
        // exit;

        $openId = $openInfo[0]['openid'];

        $unionid = $openInfo[0]['unionid'];

        if($unionid){

            $msg = 'key:'.$limit.'跳过 openID:'.$openId;

        }else{

            $ACCESS_TOKEN = $this->get_wx_access_token();

            $URL_Link = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$openId}&lang=zh_CN";
        
            $URL_jsonData = [];

            $res = $model->send_url($URL_Link,json_encode($URL_jsonData));

            $add = json_decode($res,true);

            $save = [];

            $save['unionid'] = $add['unionid'] ?? '';

            $save['subscribe_time'] = $add['subscribe_time'] ?? '';

            $save['subscribe_scene'] = $add['subscribe_scene'] ?? '';

            $result = Db::name('wx_gzh_fans')->where('openid','=',$openId)->update($save);

            $msg = 'key:'.$limit.'更新成功 openID:'.$openId;

        }

        $nextId = $limit+1;

        return resultArray(['error' => $msg, 'data'=>['nextId' => $nextId]]);

    }


    // 外部获取公众号access_token
    public function get_wx_access_token()
    {
        // echo "获取access_token";
        // exit;

        $fomateToken = file_get_contents('./token_file/accessTokenWX.json');

        $token_info = json_decode($fomateToken,true);

        // echo "<pre>";
        // print_r($token_info);
        // echo "</pre>";
        // exit;

        $nowTime = time();

        if($nowTime < $token_info['expireTime']){

            // echo '111';

            return $token_info['access_token'];

        }else{

            // echo '222';

            $access_token = $this->get_access_token_wx();

            $token_info = json_decode($access_token,true);

            return $token_info['access_token'];

        }
    }

    // 获取公众号的access_token
    public function get_access_token_wx()
    {

        $model = new SendUrlModel();

        $url = "https://api.weixin.qq.com/cgi-bin/token";

        $jsonData = [

            'grant_type' => 'client_credential',

            'appid'      => 'wx7cde54d2bb9607e6',

            'secret'     => '1aa86183eca8d6ebf854cbc0349543df',

        ];

        $data = $model->send_url($url,$jsonData);

        $fomateToken = json_decode($data,true);

        // echo "<pre>";
        // print_r($fomateToken);
        // echo "</pre>";
        // exit;

        $fomateToken['expireTime'] = time() + $fomateToken['expires_in'] - 10;

        // echo "<pre>";
        // print_r($fomateToken);
        // echo "</pre>";

        $newData = json_encode($fomateToken);

        file_put_contents('./token_file/accessTokenWX.json', $newData);

        return $newData;

    }

}